Search a 2D Matrix || Search a 2D Matrix II

Search a 2D Matrix

Question

Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties:

  • Integers in each row are sorted from left to right.
  • The first integer of each row is greater than the last integer of the previous row.

For example,

Consider the following matrix:

1
2
3
4
5
[
[1, 3, 5, 7],
[10, 11, 16, 20],
[23, 30, 34, 50]
]

Given target = 3, return true.

Analysis

Don’t treat it as a 2D matrix, just treat it as a sorted list

Code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public class Solution {
public boolean searchMatrix(int[][] matrix, int target) {
if(matrix==null||matrix.length==0)
return false;
int row=matrix.length;
int col=matrix[0].length;
int left=0;
int right=row*col-1;
while(left<=right){
int mid=(left+right)/2;
int i=mid/col;
int j=mid%col;
if(target==matrix[i][j]) return true;
else if(target>matrix[i][j]) left=mid+1;
else right=mid-1;
}
return false;
}
}

Search a 2D Matrix II

Question

Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties:

  • Integers in each row are sorted in ascending from left to right.
  • Integers in each column are sorted in ascending from top to bottom.

For example,

Consider the following matrix:

1
2
3
4
5
6
7
[
[1, 4, 7, 11, 15],
[2, 5, 8, 12, 19],
[3, 6, 9, 16, 22],
[10, 13, 14, 17, 24],
[18, 21, 23, 26, 30]
]

Given target = 5, return true.

Given target = 20, return false.

Analysis

My concise O(m+n) Java solution

从右上角的元素开始扫描,若当前元素小于target,说明整行元素都小于target,向下移动col;若大于target,则向左移动row,无嵌套循环

Code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public class Solution {
public boolean searchMatrix(int[][] matrix, int target) {
if(matrix==null||matrix.length==0)
return false;
int row=0;
int col=matrix[0].length-1;
while(row<=matrix.length-1&&col>=0){
if(matrix[row][col]==target)
return true;
else if(matrix[row][col]>target)
col--;
else
row++;
}
return false;
}
}